import { Article, History, Suggestion } from "@/types/data";
import { SearchAction } from "@/types/store";
import { getLocalHistories } from "@/utils/storage";

type SearchState = {
  suggestion: Suggestion
  history: History
  result: {
    results: Article[]
    total_count: number
  }
}

const initialState: SearchState = {
  suggestion: [],
  history: getLocalHistories(),
  result: {
    results: [],
    total_count: 10
  }
}

export default function search(state=initialState, action: SearchAction) {
  if (action.type === 'search/suggestion') {
    return {
      ...state,
      suggestion: action.payload
    }
  }
  if (action.type === 'search/set_history') {
    return {
      ...state,
      history: action.payload
    }
  }
  if (action.type === 'search/saveResults') {
    const oldResults = state.result.results;
    const {total_count, results} = action.payload
    return {
      ...state,
      result: {
        total_count,
        results: [...oldResults, ...results]
      }
    }
  }
  if (action.type === 'search/clearResults') {
    return {
      ...state,
      result: {
        total_count: 1,
        results: []
      }
    }
  }
  return state
}